package com.aiyige.page.my.localVideo;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.provider.MediaStore.Video.Media;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class SysFileHelper {
	ContentResolver cr;
	
	@SuppressLint("UseSparseArrays")
	private static HashMap<Integer,String> imghash = new HashMap<Integer, String>();
	private static HashMap<Integer,String> videohash = new HashMap<Integer, String>();

	public static List<SysFileInfo> selectList = new ArrayList<SysFileInfo>();


	public SysFileHelper(Context context) {
		cr = context.getContentResolver();
	}

	private boolean hasContains(List<SysFolderInfo> list, int bucketId) {
		for (SysFolderInfo info : list) {
			if (info.getId() == bucketId) {
				// 重复数据
				return true;
			}
		}
		return false;
	}

	/**
	 *  获取视频文件夹
	 * @return
	 */
	public List<SysFolderInfo> getVideoFolders() {
		List<SysFolderInfo> list = new ArrayList<SysFolderInfo>();

		String[] mediaColumns = new String[] { Media._ID,
				Media.BUCKET_ID, Media.BUCKET_DISPLAY_NAME };
		Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, mediaColumns, null,
				null, Media.DATE_TAKEN + " desc");
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						int id = cur.getInt(cur
								.getColumnIndexOrThrow(Media._ID));
						int bucketId = cur.getInt(cur
								.getColumnIndexOrThrow(Media.BUCKET_ID));
						String name = cur.getString(cur
								.getColumnIndexOrThrow(Media.BUCKET_DISPLAY_NAME));
						int duration = cur.getInt(cur
								.getColumnIndexOrThrow(Media.DURATION));
						Log.i("",""+duration);
						if (!hasContains(list, bucketId)) {
							SysFolderInfo info = new SysFolderInfo();
							info.setId(bucketId);
							info.setName(name);
							info.setImgPath(getVideoThumbPath(id));
							info.setItemCount(getVideosCount(bucketId));
							list.add(info);
						}

					} while (cur.moveToNext());
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}

		}
		return list;
	}

	/**
	 * 获取所有视频
	 * @return
	 */
	public List<SysFileInfo> getAllVideos() {
		List<SysFileInfo> list = new ArrayList<SysFileInfo>();

		String[] mediaColumns = new String[] { Media.DATA,
				Media._ID, Media.TITLE,
				Media.DISPLAY_NAME, Media.SIZE, Media.DURATION };

		Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, mediaColumns, null,
				null, Media.DATE_TAKEN + " desc");

		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						int duration = cur.getInt(cur
								.getColumnIndexOrThrow(Media.DURATION));
						int minutes = duration / 60000;
						// 根据产品需求，将小于5秒和大于10分钟的视频 屏蔽掉
						if (duration < 5000 || minutes > 10) {
							continue;
						}
						SysFileInfo info = new SysFileInfo();
						info.setId(cur.getInt(cur
								.getColumnIndexOrThrow(Media._ID)));
						info.setPath(cur.getString(cur
								.getColumnIndexOrThrow(Media.DATA)));
						info.setName(cur.getString(cur
								.getColumnIndexOrThrow(Media.TITLE)));
						info.setSize(cur.getLong(cur
								.getColumnIndexOrThrow(Media.SIZE)));
						info.setDuration(cur.getLong(cur
								.getColumnIndexOrThrow(Media.DURATION)));

						if (!isValidFile(info.getPath())) {
							continue;
						}
						list.add(info);
					} while (cur.moveToNext());
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}
		}
		return list;
	}

	/**
	 * 指定查询视频
	 */

	public SysFileInfo getVideos(String string) {
		 SysFileInfo info = null;
		String[] mediaColumns = new String[] { Media.DATA,
				Media._ID, Media.TITLE,
				Media.DISPLAY_NAME, Media.SIZE, Media.DURATION };

		Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, mediaColumns,Media.DATA + "=" + string,
				null, null);
		if (null != cur) {
			info = new SysFileInfo();
						info.setId(cur.getInt(cur
								.getColumnIndexOrThrow(Media._ID)));
						info.setPath(cur.getString(cur
								.getColumnIndexOrThrow(Media.DATA)));
						info.setName(cur.getString(cur
								.getColumnIndexOrThrow(Media.TITLE)));
						info.setSize(cur.getLong(cur
								.getColumnIndexOrThrow(Media.SIZE)));
						info.setDuration(cur.getLong(cur
								.getColumnIndexOrThrow(Media.DURATION)));
			}
				IOUtils.closeCursorSilently(cur);

		return info;
	}




	/**
	 * 获取视频列表
	 * @param bucketId
	 * @return
	 */
	public List<SysFileInfo> getVideoList(int bucketId) {
		List<SysFileInfo> list = new ArrayList<SysFileInfo>();

		String[] mediaColumns = new String[] { Media.DATA,
				Media._ID, Media.TITLE,
				Media.DISPLAY_NAME, Media.SIZE, Media.DURATION };

		Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, mediaColumns, Media.BUCKET_ID + "=?",
				new String[] { String.valueOf(bucketId) }, Media.DATE_TAKEN + " desc");
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						SysFileInfo info = new SysFileInfo();
						info.setId(cur.getInt(cur
								.getColumnIndexOrThrow(Media._ID)));
						info.setPath(cur.getString(cur
								.getColumnIndexOrThrow(Media.DATA)));
						info.setName(cur.getString(cur
								.getColumnIndexOrThrow(Media.TITLE)));
						info.setSize(cur.getLong(cur
								.getColumnIndexOrThrow(Media.SIZE)));
						info.setDuration(cur.getLong(cur
								.getColumnIndexOrThrow(Media.DURATION)));
						info.setImgPath(getVideoThumbPath(info.getId()));
						list.add(info);
					} while (cur.moveToNext());

				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}

		}
		return list;
	}

	/**
	 * 获取目录下视频数
	 * @param bucketId
	 * @return
	 */
	public int getVideosCount(int bucketId) {
		int count = 0;
		String[] mediaColumns = new String[] {"count(*)"};
		Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, mediaColumns, Media.BUCKET_ID + "=?",
				new String[] { String.valueOf(bucketId) }, Media.DATE_TAKEN + " desc");
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					count = cur.getInt(0);
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}
		}
		return count;
	}


	/**
	 * 获取视频缩略图
	 * @param id
	 * @return
	 */
	public String getVideoThumbPath(int id) {
		String thumbPath = null;

		String[] thumbColumns = new String[] {
				MediaStore.Video.Thumbnails.DATA,
				MediaStore.Video.Thumbnails.VIDEO_ID };

		String selection = MediaStore.Video.Thumbnails.VIDEO_ID + "=?";
		String[] selectionArgs = new String[] { id + "" };
		Cursor thumbCursor = cr.query(
				MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
				thumbColumns, selection, selectionArgs, null);
		if (null != thumbCursor) {
			try {
				if (thumbCursor.moveToFirst()) {
					thumbPath = thumbCursor
							.getString(thumbCursor
									.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA));
				}
			} finally {
				IOUtils.closeCursorSilently(thumbCursor);
			}
		}

		return thumbPath;
	}



	/**
	 *  获取音频文件夹
	 * @return
	 */
	public List<SysFolderInfo> getAudioFolders() {
		List<SysFolderInfo> list = new ArrayList<SysFolderInfo>();

		String[] mediaColumns = new String[] { MediaStore.Audio.Media._ID,
				MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.ALBUM };
		Cursor cur = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mediaColumns, null,
				null, null);
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						int Id = cur.getInt(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
						int bucketId = cur.getInt(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
						String name = cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
						if (!hasContains(list, bucketId)) {
							SysFolderInfo info = new SysFolderInfo();
							info.setId(bucketId);
							info.setName(name);
							info.setItemCount(getAudiosCount(bucketId));
							list.add(info);
						}

					} while (cur.moveToNext());
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}
		}

		return list;
	}

	/**
	 * 获取所有音频
	 * @return
	 */
	public List<SysFileInfo> getAllAudios() {
		List<SysFileInfo> list = new ArrayList<SysFileInfo>();
		String[] mediaColumns = new String[] {  MediaStore.Audio.Media.DATA,
				MediaStore.Audio.Media._ID,  MediaStore.Audio.Media.TITLE,
				MediaStore.Audio.Media.DISPLAY_NAME,  MediaStore.Audio.Media.SIZE,  MediaStore.Audio.Media.DURATION };
		Cursor cur = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mediaColumns, null, null, null);
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						SysFileInfo info = new SysFileInfo();
						info.setId(cur.getInt(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)));
						info.setPath(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
						info.setName(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
						info.setSize(cur.getLong(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)));
						info.setDuration(cur.getLong(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)));

						list.add(info);
					} while (cur.moveToNext());
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}
		}
		return list;
	}

	/**
	 * 获取音频列表
	 * @param album_id
	 * @return
	 */
	public List<SysFileInfo> getAudioList(int album_id) {
		List<SysFileInfo> list = new ArrayList<SysFileInfo>();

		String[] mediaColumns = new String[] {  MediaStore.Audio.Media.DATA,
				MediaStore.Audio.Media._ID,  MediaStore.Audio.Media.TITLE,
				MediaStore.Audio.Media.DISPLAY_NAME,  MediaStore.Audio.Media.SIZE,  MediaStore.Audio.Media.DURATION };

		Cursor cur = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mediaColumns, MediaStore.Audio.Media.ALBUM_ID + "=?",
				new String[] { String.valueOf(album_id) }, null);
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						SysFileInfo info = new SysFileInfo();
						info.setId(cur.getInt(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)));
						info.setPath(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
						info.setName(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
						info.setSize(cur.getLong(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)));
						info.setDuration(cur.getLong(cur
								.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)));

						list.add(info);
					} while (cur.moveToNext());
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}

		}
		return list;
	}

	/**
	 * 获取目录下音频频数
	 * @param folderId
	 * @return
	 */
	public int getAudiosCount(int folderId) {
		int count = 0;
		String[] mediaColumns = new String[] {"count(*)"};
		Cursor cur = null;
		try {
			cur = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mediaColumns, MediaStore.Audio.Media.ALBUM_ID + "=?",
					new String[] { String.valueOf(folderId) }, null);
			if (null != cur) {
				if (cur.moveToFirst()) {
					count = cur.getInt(0);
				}
			}
		} finally {
			IOUtils.closeCursorSilently(cur);
		}
		return count;
	}


	/**
	 *  获取图片文件夹
	 * @return
	 */
	public List<SysFolderInfo> getImageFolders() {
		List<SysFolderInfo> list = new ArrayList<SysFolderInfo>();

		String[] mediaColumns = new String[] { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.BUCKET_ID, MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
				MediaStore.Images.Media.DATA};
		Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mediaColumns, null,
				null, null);
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						int id = cur.getInt(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
						int bucketId = cur.getInt(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID));
						String name = cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME));
						//					String path = cur.getString(cur
						//							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
						String path = getThumbImagePath(id);
						if (!hasContains(list, bucketId)) {
							SysFolderInfo info = new SysFolderInfo();
							info.setId(bucketId);
							info.setName(name);
							info.setImgPath(path);
							info.setItemCount(getImagesCount(bucketId));
							list.add(info);
						}

					} while (cur.moveToNext());
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}

		}

		return list;
	}

	/**
	 * 获取所有图片
	 * @return
	 */
	public List<SysFileInfo> getAllImages() {
		List<SysFileInfo> list = new ArrayList<SysFileInfo>();

		final Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		Cursor cur = cr.query(images, null, null, null,
				MediaStore.Images.Media.DATE_MODIFIED + " DESC");
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						SysFileInfo info = new SysFileInfo();
						info.setId(cur.getInt(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media._ID)));
						info.setPath(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)));
						info.setName(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)));
						info.setSize(cur.getLong(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)));
						info.setImgPath(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)));

						if (!isValidFile(info.getPath())) {
							continue;
						}
						list.add(info);

					} while (cur.moveToNext());
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}

		}
		return list;
	}

	/**
	 * 获取图片列表
	 * @param bucket_id
	 * @return
	 */
	public List<SysFileInfo> getImageList(int bucket_id) {
		List<SysFileInfo> list = new ArrayList<SysFileInfo>();

		String[] mediaColumns = new String[] {  MediaStore.Images.Media.DATA,
				MediaStore.Images.Media._ID,  MediaStore.Images.Media.TITLE,
				MediaStore.Images.Media.DISPLAY_NAME,  MediaStore.Images.Media.SIZE};

		Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mediaColumns, MediaStore.Images.Media.BUCKET_ID + "=?",
				new String[] { String.valueOf(bucket_id) }, null);
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
					do {
						SysFileInfo info = new SysFileInfo();
						info.setId(cur.getInt(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media._ID)));
						info.setPath(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)));
						info.setName(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)));
						info.setSize(cur.getLong(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)));
						info.setImgPath(cur.getString(cur
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)));
						info.setThumb(getThumbImagePath(info.getId()));
						list.add(info);


					} while (cur.moveToNext());
				}
			} finally {
				IOUtils.closeCursorSilently(cur);
			}
		}
		return list;
	}

	/**
	 * 获取目录下图片频数
	 * @param folderId
	 * @return
	 */
	public int getImagesCount(int folderId) {
		int count = 0;
		String[] mediaColumns = new String[] {"count(*)"};
		Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mediaColumns, MediaStore.Images.Media.BUCKET_ID + "=?",
				new String[] { String.valueOf(folderId) }, null);
		if (null != cur) {
			try {
				if (cur.moveToFirst()) {
                    count = cur.getInt(0);
				}
			} finally {
              IOUtils.closeCursorSilently(cur);
			}
		}

		return count;
	}

	public String getThumbImagePath(int id) {
		String url = null;
		String[] projection = { Thumbnails.IMAGE_ID,
				Thumbnails.DATA };
		Cursor cursor = cr.query(
				Thumbnails.EXTERNAL_CONTENT_URI, projection,
				Thumbnails.IMAGE_ID + " = ?",
				new String[] { String.valueOf(id) }, null);

		if (null != cursor) {
			try {
				if (cursor.moveToFirst()) {
                    url = cursor.getString(1);
				}
			} finally {
				IOUtils.closeCursorSilently(cursor);
			}
		}

		return url;
	}

	public  void getAllImageThumbnails() {
		imghash.clear();
		final String[] projection = new String[] { Thumbnails._ID,
				Thumbnails.IMAGE_ID, Thumbnails.DATA };
		final Uri images = Thumbnails.EXTERNAL_CONTENT_URI;
		Cursor cursor = null;
		try {
			cursor = cr.query(images, projection, null, null,
					Thumbnails._ID + " DESC");
			if (cursor != null && cursor.moveToFirst()) {
				int imageID;
				String imagePath;
				do {
					imageID = cursor.getInt(cursor.getColumnIndex(Thumbnails.IMAGE_ID));
					imagePath = cursor.getString(cursor.getColumnIndex(Thumbnails.DATA));
					imghash.put(imageID, imagePath);
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			IOUtils.closeCursorSilently(cursor);
        }
	}
	
	
	public String getThumbnailWithImageID(int key, String defalt){
		if(imghash == null || !imghash.containsKey(key)) {
			return defalt;
		}
		
		try{
			String thumbFilePath = imghash.get(key);
			if(TextUtils.isEmpty(thumbFilePath)){
				return defalt;
			}
			return thumbFilePath;
		}catch(Exception e){}

		return defalt;
	}
	
	/**
	 * 获取视频缩略图
	 * @return
	 */
	public void getAllVideoThumbnails() {
		videohash.clear();
		
		final String[] projection = new String[] { MediaStore.Video.Thumbnails._ID,
				MediaStore.Video.Thumbnails.VIDEO_ID, MediaStore.Video.Thumbnails.DATA };
		final Uri videos = MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI;
		Cursor cursor = null;
		try {
			cursor = cr.query(videos, projection, null, null,
					MediaStore.Video.Thumbnails._ID + " DESC");
			if (cursor != null && cursor.moveToFirst()) {
				int videoID;
				String imagePath;
				do {
					videoID = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Thumbnails.VIDEO_ID));
					imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
					videohash.put(videoID, imagePath);
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			IOUtils.closeCursorSilently(cursor);
        }
	}
	
	public String getThumbnailWithVideoID(int key, String defalt){
		if(videohash == null || !videohash.containsKey(key)) {
			return defalt;
		}
		
		try{
			String thumbFilePath = videohash.get(key);
			if(TextUtils.isEmpty(thumbFilePath)){
				return defalt;
			}
			
			return thumbFilePath;
		}catch(Exception e){}

		return defalt;
	}
	
	private static boolean isValidFile(String filePath) {
		if (TextUtils.isEmpty(filePath)) {
			return false;
		}

		File imageFile = new File(filePath);
		if (imageFile.exists()) {
			return true;
		}

		return false;
	}
	
	public void clear() {
		imghash.clear();
		videohash.clear();
		selectList.clear();
	}
}
